//
//  ViewController.swift
//  NewCard
//
//  Created by yihui on 2017/11/16.
//  Copyright © 2017年 yihui. All rights reserved.
//

import UIKit

class UserViewController: UIViewController {

    // contectView 所有控件的容器view
    fileprivate lazy var contectView : UIView = {
        let contectView = UIView()
        contectView.frame = self.view.bounds
        contectView.backgroundColor = UIColor.white
        return contectView
    }()
    // 图标iconImageView
    fileprivate lazy var iconImageView: UIImageView = {
        let iconImageView = UIImageView(image: #imageLiteral(resourceName: "timg"))
        let w : CGFloat = 200
        let h : CGFloat = 300
        let x : CGFloat = (self.contectView.width - w) * 0.5
        let y : CGFloat = (self.contectView.height - h) * 0.5 - 100
        iconImageView.frame = CGRect(x: x, y: y, width: w, height: h)
        return iconImageView
    }()
    // 密码问题TextField
    fileprivate lazy var PWProblemField: UITextField = {
        let w : CGFloat = 200
        let h : CGFloat = 30
        let x : CGFloat = (self.contectView.width - w) * 0.5
        let y : CGFloat = self.iconImageView.bottom + 20
        let PWProblemField = UITextField(frame: CGRect(x: x, y: y, width: w, height: h),
                                         alpha: 0,
                                         placeholder: "设置找回密码的提示问题")
        PWProblemField.delegate = self
        return PWProblemField
    }()
    // 密码答案TextField
    fileprivate lazy var PWAnswerField: UITextField = {
        let w : CGFloat = 200
        let h : CGFloat = 30
        let x : CGFloat = (self.contectView.width - w) * 0.5
        let y : CGFloat = self.PWProblemField.bottom + 10
        let PWAnswerField = UITextField(frame: CGRect(x: x, y: y, width: w, height: h),
                                        alpha: 0,
                                        placeholder: "设置找回密码的答案")
        PWAnswerField.delegate = self
        return PWAnswerField
    }()
    // 密码TextField
    fileprivate lazy var PassWordField: UITextField = {
        let w : CGFloat = 200
        let h : CGFloat = 30
        let x : CGFloat = (self.contectView.width - w) * 0.5
        let y : CGFloat = self.iconImageView.bottom + 100
        let PassWordField = UITextField(frame: CGRect(x: x, y: y, width: w, height: h),
                                        placeholder: "设置密码")
        PassWordField.isSecureTextEntry = true
        PassWordField.delegate = self
        return PassWordField
    }()
    // 问号按钮
    fileprivate lazy var questionMarkButton: UIButton = {
        
        let w: CGFloat = 30
        let h: CGFloat = 30
        let x: CGFloat = 0
        let y: CGFloat = self.PassWordField.y
        let questionMarkButton = UIButton(frame: CGRect(x: x, y: y, width: w, height: h),
                                          titleColorNormal: .red,
                                          title: "?")
        questionMarkButton.left = self.PassWordField.right
        questionMarkButton.setTitleColor(UIColor.red, for: .normal)
        questionMarkButton.isHidden = true
        questionMarkButton.tag = 0
        questionMarkButton.addTarget(self, action: #selector(self.questionMarkBtnClick(_:)), for: .touchUpInside)
        return questionMarkButton
    }()
    // Ligon登录按钮
    fileprivate lazy var loginButton: UIButton = {
        let w: CGFloat = 200
        let h: CGFloat = 30
        let x: CGFloat = (self.contectView.width - w) * 0.5
        let y: CGFloat = self.PassWordField.bottom + 10
        let loginButton = UIButton(frame: CGRect(x: x, y: y, width: w, height: h),
                                   backColor: .orange,
                                   cornerRadius: 5,
                                   title: "首次使用请先设置密码")
        loginButton.tag = 0
        loginButton.addTarget(self, action: #selector(self.loginBtnClick(_:)), for: .touchUpInside)
        return loginButton
    }()
    // 注册或登录
    fileprivate var isPass : Bool = false
    // 登录按钮和密码框动画上下移动的偏移量
    fileprivate var loginButtonOffset : CGFloat = 0
    fileprivate var PassWordFieldOffset : CGFloat = 0
    // 保存所有 UITextField 的 frame
    fileprivate var Frame : CGRect!
    // 数据源 
    fileprivate var models : [UserModel]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载数据源
        loadData()
        // 加载UI
        setupUI()
        // 通知
        setupNotification()
        
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
        //HHLog("销毁")
    }
}

//MARK: -- UI界面设置
extension UserViewController {
    fileprivate func setupUI() {
        // 加载控件
        view.addSubview(contectView)
        contectView.addSubview(iconImageView)
        contectView.addSubview(PWProblemField)
        contectView.addSubview(PWAnswerField)
        contectView.addSubview(PassWordField)
        contectView.addSubview(loginButton)
        contectView.addSubview(questionMarkButton)
        // 加载动画
        setupAnimate()
    }
    // 设置动画
    private func setupAnimate() {
        
        iconImageViewAnimateTranslation()
        
        if (models?.count)! > 0 {
            isPass = true
        }
        
        if !isPass { // 注册界面执行这里
            
            PWProblemFieldAnimateTranslation()
            PWAnswerFieldAnimateTranslation()
            
        } else { // 登录界面执行这里
            
            PassWordFieldOffset = PassWordField.y - PWProblemField.y
            PassWordField.y -= PassWordFieldOffset
            loginButtonOffset = loginButton.y - PWAnswerField.y
            PassWordField.placeholder = "请输入密码"
            loginButton.setTitle("登 录", for: .normal)
            loginButton.tag = 1
            loginButton.y -= loginButtonOffset
            
            questionMarkButton.y = PassWordField.y
            questionMarkButtonAnimateFadeout()
        }
        
        PassWordFieldAnimateTranslation()
        loginButtonAnimateFadeout()
    }
    private func iconImageViewAnimateTranslation() {
        iconImageView.centerY = -iconImageView.centerY
        animateTranslation(iconImageView, 1.0, 0.25, CGPoint(x: iconImageView.centerX, y: -iconImageView.centerY))
    }
    private func PWProblemFieldAnimateTranslation() {
        PWProblemField.alpha = 1.0
        PWProblemField.centerX = -PWProblemField.centerX
        animateTranslation(PWProblemField, 1.0, 0.5, CGPoint(x: contectView.centerX, y: PWProblemField.centerY))
    }
    private func PWAnswerFieldAnimateTranslation() {
        PWAnswerField.alpha = 1.0
        PWAnswerField.centerX = -PWAnswerField.centerX
        animateTranslation(PWAnswerField, 1.0, 0.75, CGPoint(x: contectView.centerX, y: PWAnswerField.centerY))
    }
    private func PassWordFieldAnimateTranslation() {
        PassWordField.centerX = -PassWordField.centerX
        animateTranslation(PassWordField, 1.0, 1.0, CGPoint(x: contectView.centerX, y: PassWordField.centerY))
    }
    fileprivate func loginButtonAnimateFadeout() {
        loginButton.alpha = 0
        animateFadeout(loginButton, 1.0, 1.25)
    }
    fileprivate func questionMarkButtonAnimateFadeout() {
        questionMarkButton.isHidden = false
        questionMarkButton.alpha = 0
        animateFadeout(questionMarkButton, 1.0, 1.5)
    }
    fileprivate func PWProblemFieldAnimateFadeout() {
        PWProblemField.alpha = 0
        animateFadeout(PWProblemField, 1.0, 0.25)
    }
    fileprivate func  PWAnswerFieldAnimateFadeout() {
        PWAnswerField.alpha = 0
        animateFadeout(PWAnswerField, 1.0, 0.5)
    }
    fileprivate func  PassWordFieldAnimateFadeout() {
        PassWordField.alpha = 0
        animateFadeout(PassWordField, 1.0, 0.75)
    }
}

//MARK: -- 动画封装
extension UserViewController {
    // 淡出动画
    fileprivate func animateFadeout(_ target: UIView,_ duration: TimeInterval,_ delay: TimeInterval) {
        
        UIView.animate(withDuration: duration, delay: delay, options: .curveEaseOut, animations: {
            target.alpha = 1.0
        }) { (finished) -> Void in
            
           // HHLog("动画执行完成")
        }
    }
    
    // 平移动画
    fileprivate func animateTranslation(_ target: UIView,_ duration: TimeInterval,_ delay: TimeInterval, _ center:CGPoint){
        UIView.animate(withDuration: duration , delay: delay, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.3, options: .curveEaseOut ,animations: { () -> Void in
            
            target.center = center
            
        }) { (finished) -> Void in
            
           // HHLog("动画执行完成")
        }
    }
}

//MARK: -- 点击事件
extension UserViewController {
    // 问号按钮点击事件
    @objc fileprivate func questionMarkBtnClick(_ btn : UIButton) {
        // 找回密码界面切换
        if btn.tag == 0 {
            btn.tag = 1
            btntagOne()
        } else if btn.tag == 1 { // 登录界面切换
            btn.tag = 0
            btntagTwo()
        }
    }
    // 登录按钮点击事件
    @objc fileprivate func loginBtnClick(_ btn : UIButton) {
        
        guard let pass = PassWordField.text, PassWordField.text != "" else {
            Tools.show(self, message: "请先输入密码!")
            return
        }
        
        // 登录
        if btn.tag == 1  {

            if models?.first?.passWord == pass {
                // 跳转到详情页
                PassWordField.text = nil
                self.performSegue(withIdentifier: "Details", sender: nil)
                return
            } else { Tools.show(self, message: "密码错误") }
        }
        
        guard let problem = PWProblemField.text, PWProblemField.text != "" else { return }
        guard let answer = PWAnswerField.text, PWAnswerField.text != "" else {
            Tools.show(self, message: "请先输入正确的答案")
            return
        }
        
        // 注册密码
        if btn.tag == 0 {
            // 保存信息到数据库
            guard OpenData.insertData(data: setupData(pass, problem , answer)) else {
                HHLog("插入数据失败")
                return
            }
            loadData()
            Tools.show(self, message: "设置成功")
            isPass = true
            btntagTwo()
        }
        
        // 找回密码
        if btn.tag == 2 {
            if (models?.first?.answer)?.uppercased() == answer.uppercased().trimmingCharacters(in: .whitespaces) {
                // 保存信息到数据库
                guard OpenData.updateData(data: setupData(pass, problem , answer)) else {
                    //HHLog("修改资料失败")
                    return
                }
                loadData()
                Tools.show(self, message: "资料修改成功")
                btntagTwo()
            } else { Tools.show(self, message: "请先输入正确的答案") }
        }
    }
    // tag 0 找回密码界面相关设置
    private func btntagOne() {
        PWProblemField.text = models?.first?.problem
        PWProblemField.isEnabled = false
        PWProblemField.alpha = 1.0
        PWProblemField.placeholder = "问题"
        questionMarkButton.setTitle("<-", for: .normal)
        PWAnswerField.alpha = 1.0
        PWAnswerField.placeholder = "请输入找回密码的问题答案"
        PassWordField.y += PassWordFieldOffset
        PassWordField.placeholder = "请输入新密码"
        PassWordField.text = nil
        loginButton.y += loginButtonOffset
        loginButton.setTitle("找回密码", for: .normal)
        loginButton.tag = 2
        PWProblemFieldAnimateFadeout()
        questionMarkButtonAnimateFadeout()
        PWAnswerFieldAnimateFadeout()
        PassWordFieldAnimateFadeout()
        loginButtonAnimateFadeout()
    }
    // tag 1 登录界面相关设置
    private func btntagTwo() {
        
        PWProblemField.alpha = 0
        questionMarkButton.setTitle("?", for: .normal)
        PWAnswerField.alpha = 0
        PassWordField.y -= PassWordFieldOffset
        loginButton.y -= loginButtonOffset
        PassWordField.placeholder = "请输入密码"
        loginButton.setTitle("登 录", for: .normal)
        loginButton.tag = 1
        questionMarkButton.tag = 0
        questionMarkButtonAnimateFadeout()
        PassWordFieldAnimateFadeout()
        loginButtonAnimateFadeout()
    }
}

//MARK: -- 创建 UITextField , UITextFieldDelegate
extension UserViewController : UITextFieldDelegate {

//    fileprivate func addUITextField() -> UITextField {
//        
//        let w : CGFloat = 200
//        let h : CGFloat = 30
//        let x : CGFloat = (contectView.width - w) * 0.5
//        let y : CGFloat = 0
//        let textField = UITextField(frame: CGRect(x: x, y: y, width: w, height: h))
//        // 设置 样式 (.none 无边框  .line 直线边框  .roundedRect 圆角矩形边框  .bezel 边线+阴影)
//        textField.borderStyle = UITextBorderStyle.roundedRect
//        // 设置 文字大小
//        textField.font = UIFont.systemFont(ofSize: 14)
//        // 设置 水平对齐
//        textField.textAlignment = NSTextAlignment.left // 居中对齐
//        // 设置 清理按钮 (.never 从不出现 .whileEditing 编辑时出现 .unlessEditing 编辑时不出现 编辑完后出现 .always 一直出现)
//        textField.clearButtonMode = UITextFieldViewMode.whileEditing
//        //  设置 键盘样式
//        textField.keyboardType = UIKeyboardType.default
//        // 设置 代理
//        textField.delegate = self
//
//        return textField
//    }
//    
    // 通知
    fileprivate func setupNotification() {
        // 键盘监听通知
        NotificationCenter.default.addObserver(self, selector: #selector(self.kbFrameChanged(_:)), name: .UIKeyboardWillChangeFrame, object: nil)
    }
    
    //MARK: -- 获取当前被选择的UITextField
    func textFieldDidBeginEditing(_ textField: UITextField) {
        Frame = textField.frame
    }
    
    //MARK: -- Return 关闭键盘
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        textField.resignFirstResponder()
        
        return true
    }
    //MARK: --<#name> 弹出键盘上移UI
    @objc fileprivate func kbFrameChanged( _ notification : Notification) {
        
        let info = notification.userInfo
        let kbRect = (info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let bottomSpacing: CGFloat = 50
        let maxY = view.frame.height - (Frame.maxY + bottomSpacing)
        let offset : CGFloat = maxY - kbRect.height
        let offsetY : CGFloat = (kbRect.origin.y < view.frame.height) ? offset : 0
        if (kbRect.height) > (view.bounds.height-Frame.maxY-bottomSpacing) {
            UIView.animate(withDuration: 0.3) {
                self.contectView.transform = CGAffineTransform(translationX: 0, y: offsetY)
            }
        }
    }
    //MARK: -- 关闭空白处关闭键盘
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}

//MARK: -- 获取数据
extension UserViewController {
    
    fileprivate func loadData() {
        let array = OpenData.loadData(.User)
        var tempArr = [UserModel]()
        for arr in array! {
            tempArr.append(UserModel(dict:arr))
        }
        models = tempArr
    }
    
    // 把数据包装后传递
    fileprivate func setupData(_ pass : String,_ problem : String,_ answer : String) -> UserModel {
        let data = UserModel()
        data.passWord = pass
        data.problem = problem
        data.answer = answer
        return data
    }
}
